<template>
  <el-dialog
    :title="$t('msg.excel.roleDialogTitle')"
    :model-value="modelValue"
    @close="closed"
    width="500"
  >
    <el-tree
      ref="treeRef"
      :data="allPermission"
      show-checkbox
      check-strictly
      node-key="id"
      default-expand-all
      :props="defaultProps"
    ></el-tree>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closed">{{ $t('msg.universal.cancel') }}</el-button>
        <el-button type="primary" @click="onConfirm">{{
          $t('msg.universal.confirm')
        }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineProps, defineEmits, ref, ElMessage, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import {
  permissionList,
  rolePermission,
  distributePermission
} from '@/api/role'
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  roleId: {
    type: String,
    required: true
  }
})
const emits = defineEmits(['update:modelValue'])

const i18n = useI18n()
const onConfirm = async () => {
  await distributePermission({
    roleId: props.roleId,
    permissions: treeRef.value.getCheckedKeys()
  })
  ElMessage.success(i18n.t('msg.role.updateRoleSuccess'))
  closed()
}

const closed = () => {
  emits('update:modelValue', false)
}

const allPermission = ref([])
const getPermissionList = async () => {
  const { data } = await permissionList()
  allPermission.value = data.data
}

const defaultProps = {
  children: 'children',
  label: 'permissionName'
}

getPermissionList()

const treeRef = ref(null)
const getRolePermission = async () => {
  const { data } = await rolePermission(props.roleId)
  const checkedKeys = data.data
  treeRef.value.setCheckedKeys(checkedKeys)
}

watch(
  () => props.roleId,
  (val) => {
    if (val) getRolePermission()
  }
)
</script>

<style lang="scss" scoped></style>
